﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Linq;
using System.Text;

namespace Study
{
    public partial class xml数据导入condition表 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            /*
            
            */
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlParameter[] ps={
                              new SqlParameter("@filter",SqlDbType.NVarChar,1000),
                              new SqlParameter("@id",SqlDbType.Int)
                              };
  
            ps[0].Value="CustomField1='111'";
            
            ps[1].Direction = ParameterDirection.Output; //设置参数为输出参数
            DBAccess.ExecuteNonQueryProc("sp_addCondition", ps);
            object result = ps[1].Value;//获取输出参数值
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            string sql_del = "delete from TB_Condition where 1=1";
            string sql_truncate = "truncate table TB_Condition";
            DBAccess.ExecuteNonQuery(sql_del);
            DBAccess.ExecuteNonQuery(sql_truncate);

            string rootPath = HttpContext.Current.Server.MapPath("/");
            string filePath = Path.Combine(rootPath, "Files/MainMenu.xml");
            XmlDocument xml = new XmlDocument();
            xml.Load(filePath);//注：若要加载字符串xml，则调用LoadXml()方法即可
            XmlNode xd = xml.SelectSingleNode("//Menu");//获取xml文档根节点
            XmlNodeList list_item = xd.SelectNodes("MenuItem");//获取所有MenuItem节点

            List<MenuItem> menuItems = new List<MenuItem>();
            int miId = 1;
            for (int i = 0; i < list_item.Count; i++)
            {
                MenuItem menuItem = new MenuItem();
                menuItem.ClassID = list_item[i].Attributes["ClassID"].Value;
                menuItem.Name = list_item[i].Attributes["Name"].Value;

                XmlNodeList list_condition = list_item[i].SelectNodes("MICondition");

                for (int j = 0; j < list_condition.Count; j++)
                {
                    MICondition condition = new MICondition();
                    condition.Indentity = list_condition[j].Attributes["Indentity"].Value;
                    condition.Name = list_condition[j].Attributes["Name"].Value;
                    condition.Field = list_condition[j].Attributes["Field"].Value;

                    XmlNodeList list_child = list_condition[j].SelectNodes("MIChild");

                    for (int k = 0; k < list_child.Count; k++)
                    {
                        
                        MIChild miChild = new MIChild();
                        miChild.IsShowNav = list_child[k].Attributes["IsShowNav"].Value;
                        miChild.URL = list_child[k].Attributes["URL"].Value;
                        miChild.ID = miId.ToString();
                        miChild.IsShowDetailNav = list_child[k].Attributes["IsShowDetailNav"].Value;
                        miChild.Name = list_child[k].Attributes["Name"].Value;
                        miChild.ArchiveTypeID = list_child[k].Attributes["ArchiveTypeID"].Value;
                        condition.MiChilds.Add(miChild);
                        miId++;
                    }
                    menuItem.MiConditions.Add(condition);
                }
                menuItems.Add(menuItem);
            }

            for (int i = 0; i < menuItems.Count; i++)
            {
                for (int j = 0; j < menuItems[i].MiConditions.Count; j++)
                {
                    for (int k = 0; k < menuItems[i].MiConditions[j].MiChilds.Count; k++)
                    {
                        string sql = "insert into TB_Condition(checkerFilter) values(@checkerFilter)";
                        SqlParameter ps = new SqlParameter("@checkerFilter", SqlDbType.NVarChar, 50) { Value = menuItems[i].MiConditions[j].Field + "='" + menuItems[i].MiConditions[j].MiChilds[k].Name + "'" };
                        DBAccess.ExecuteNonQuery(sql, ps);
                    }
                }
            }


        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            string xml = @"<book price='100' isbn='1002310'>" +
                    "<title>XClarity Samples</title>" +
                    "<author>Matt</author>" +
                 "</book>";
            XDocument doc = XDocument.Parse(xml);
            doc.Save("c:\\Temp.xml");
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            List<MenuItem> list = new List<MenuItem>();

            string sql_arcClass = "select ID,Name,FolderTypeID from TB_Class  FolderTypeID";
            DataTable dt_arcClass = DBAccess.ExecuteDataTable(sql_arcClass);
            if (dt_arcClass != null && dt_arcClass.Rows.Count > 0)
            {
                int m1=1;
                int m2 = 1;
                for (int i = 0; i < dt_arcClass.Rows.Count; i++)
                {
                    MenuItem menuitem = new MenuItem();
                    menuitem.ClassID = dt_arcClass.Rows[i]["ID"].ToString().Trim();
                    menuitem.Name = dt_arcClass.Rows[i]["Name"].ToString().Trim();

                    string sql_condition = string.Format("SELECT SourceName,MapName,DropDownID FROM TB_ArchiveMap where ArchiveTypeID={0} and SourceName<>'ArchiveName'", dt_arcClass.Rows[i]["FolderTypeID"]);
                    DataTable dt_condition = DBAccess.ExecuteDataTable(sql_condition);
                    if (dt_condition != null && dt_condition.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt_condition.Rows.Count; j++)
                        {
                            MICondition micondition = new MICondition();
                            micondition.Indentity = m2.ToString();
                            m2++;
                            micondition.Name = dt_condition.Rows[j]["MapName"].ToString().Trim();
                            micondition.Field = dt_condition.Rows[j]["SourceName"].ToString().Trim();

                            string sql_child = string.Format("select DicName from TB_Dictionary where SupDicID={0}", dt_condition.Rows[j]["DropDownID"]);
                            DataTable dt_child = DBAccess.ExecuteDataTable(sql_child);
                            if (dt_child != null && dt_child.Rows.Count > 0)
                            {
                                for (int k = 0; k < dt_child.Rows.Count; k++)
                                { 
                                    MIChild michild = new MIChild();
                                    michild.IsShowNav = "0";
                                    michild.URL = "";
                                    michild.ID = m1.ToString().Trim();
                                    m1++;
                                    michild.IsShowDetailNav = "";
                                    michild.Name = dt_child.Rows[k]["DicName"].ToString().Trim();
                                    michild.ArchiveTypeID = dt_arcClass.Rows[i]["FolderTypeID"].ToString().Trim();
                                    micondition.MiChilds.Add(michild);
                                }
                            }
                            menuitem.MiConditions.Add(micondition);
                        }
                    }
                    list.Add(menuitem);
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<Config>");
            sb.Append("<Menu>");

            string sql_del = "delete from TB_Condition where 1=1";
            string sql_truncate = "truncate table TB_Condition";
            DBAccess.ExecuteNonQuery(sql_del);
            DBAccess.ExecuteNonQuery(sql_truncate);
            for (int i = 0; i < list.Count; i++)
            {
                sb.Append("<MenuItem ClassID=\""+list[i].ClassID+"\" Name=\""+list[i].Name+"\">");
                for (int j = 0; j < list[i].MiConditions.Count; j++)
                {
                    sb.Append("<MICondition Indentity=\"" + list[i].MiConditions[j].Indentity + "\" Name=\"" + list[i].MiConditions[j] .Name+ "\">");
                    for (int k = 0; k < list[i].MiConditions[j].MiChilds.Count; k++)
                    {
                        sb.Append("<MIChild IsShowNav=\"" + list[i].MiConditions[j].MiChilds[k].IsShowNav + "\" URL=\"" + list[i].MiConditions[j].MiChilds[k].URL + "\" ID=\"" + list[i].MiConditions[j].MiChilds[k].ID + "\" IsShowDetailNav=\"" + list[i].MiConditions[j].MiChilds[k].IsShowDetailNav + "\" Name=\"" + list[i].MiConditions[j].MiChilds[k].Name + "\" ArchiveTypeID=\"" + list[i].MiConditions[j].MiChilds[k].ArchiveTypeID + "\"></MIChild>");
                        string sql = "insert into TB_Condition(checkerFilter) values(@checkerFilter)";
                        SqlParameter ps = new SqlParameter("@checkerFilter", SqlDbType.NVarChar, 50) { Value = list[i].MiConditions[j].Field + "='" + list[i].MiConditions[j].MiChilds[k].Name + "'" };
                        DBAccess.ExecuteNonQuery(sql, ps);
                    }
                    sb.Append("</MICondition>");
                }
                sb.Append("</MenuItem>");
                
            }
            sb.Append("</Menu>");

            sb.Append(@"<SelfArcDetail>
            <Item TypeID='21' ClassID = '1'>
              <Field FName='ArchiveName' SName='项目代号'>
              </Field>
              <Field FName='CustomField1' SName='项目名称'>
              </Field>
              <Field FName='CustomField4' SName='项目所在地域'>
              </Field>
              <Field FName='CustomField7' SName='项目负责人'>
              </Field>
              <Field FName='CustomField44' SName='副项目负责人'>
              </Field>
              <Field FName='CustomField12' SName='总建筑面积'>
              </Field>
              <Field FName='CustomField16' SName='高度'>
              </Field>
              <Field FName='CustomField23' SName='演播室面积'>
              </Field>
              <Field FName='CustomField5' SName='设计阶段'>
              </Field>
              <Field FName='CustomField6' SName='设计内容'>
              </Field>
              <Field FName='CustomField41' SName='设计范围及主要功能'>
              </Field>
              <Field FName='CustomField22' SName='其他规模'>
              </Field>
            </Item>
          </SelfArcDetail>
          <LinkInfo Remark='列表文件夹 添加超链接'>
            <link id='19' url='http://168.168.60.39/'></link>
            <link id='18' url='http://g.wanfangdata.com.cn/'></link>
          </LinkInfo>
          <ShowColumn>
            <!-- 内置字段名称 显示Field设置的字段值 内置字段原来的值不显示 显示以下配置的值 -->
            <Column ArchiveTypeID='24' Field='CustomField27'></Column>
            <!--<Column ArchiveTypeID='35' Field='CustomField2'></Column>-->
          </ShowColumn>");

            sb.Append("</Config>");

            XDocument doc = XDocument.Parse(sb.ToString());
            FileStream fs = new FileStream("test.xml", FileMode.Create);
            doc.Save(fs,SaveOptions.DisableFormatting);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("123.xml", System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();

            
            

            //doc.Save("c:\\111.xml");

            
        }            
    }


    public class MenuItem
    {
        public string ClassID { get; set; }
        public string Name { get; set; }
        public List<MICondition> MiConditions = new List<MICondition>();            
    }

    public class MICondition
    {
        public string Indentity { get; set; }
        public string Name { get; set; }
        public string Field { get; set; }
        public List<MIChild> MiChilds = new List<MIChild>();
            
    }

    public class MIChild
    {
        public string IsShowNav { get; set; }
        public string URL { get; set; }
        public string ID { get; set; }
        public string IsShowDetailNav { get; set; }
        public string Name { get; set; }
        public string ArchiveTypeID { get; set; }
    }
}